<template>
  <!-- 添加或修改任务对话框 -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
    <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="dialog.title === '修改任务'" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务类型" prop="taskTypeId">
            <el-select v-model="form.taskTypeId" :disabled="dialog.title === '修改任务'" placeholder="请选择任务类型" clearable>
              <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-form-item v-if="xtId === form.taskTypeId" label="协调人" prop="collaborators">-->
        <!--          <task-user v-model="form.collaborators" :disabled="dialog.title === '修改任务'"></task-user>-->
        <!--        </el-form-item>-->
        <el-col :span="12">
          <el-form-item label="业绩目标" prop="performanceId">
            <person-select v-model="form.performanceId" v-model:name="form.performanceName" :disabled="dialog.title === '修改任务'"></person-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理人" prop="handlerUserName">
            <user-input v-model="form.handlerUserId" v-model:name="form.handlerUserName" :disabled="dialog.title === '修改任务'"></user-input>
          </el-form-item>
        </el-col>
        <el-col v-if="dialog.title === '修改任务'" :span="12">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="任务总绩效分" prop="taskName">-->
        <!--            <el-input v-model="form.originalScore" placeholder="请输入任务总绩效分" :disabled="dialog.title === '修改任务'" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
      <el-form-item label="任务内容">
        <editor v-model="form.content" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="预计开始时间" prop="expectedStartTime">
            <el-date-picker
              v-model="form.expectedStartTime"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计开始时间"
              :disabled="dialog.title === '修改任务'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计结束时间" prop="expectedEndTime">
            <el-date-picker
              v-model="form.expectedEndTime"
              clearable
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择预计结束时间"
              :disabled="dialog.title === '修改任务'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="附件（多个）" prop="enclosure">
        <file-upload v-model="form.enclosure" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button>取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="TaskEdit" lang="ts">
/**
 * 这个编辑是留给主页 面板去编辑的，但是目前没有用到
 */
import { defineProps } from 'vue';
import { getTask } from '@/api/task/task';
import { addTask, updateTask } from '@/api/task/task';
import PersonSelect from '@/views/target/person/PersonSelect.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { task_status, user_type, review_status } = toRefs<any>(proxy?.useDict('task_status', 'user_type', 'review_status'));

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const props = defineProps<{
  modelValue?: string | number;
  taskId?: number;
  visible?: boolean;
}>();

const emit = defineEmits(['update:modelValue', 'update:taskId', 'update:visible']);
const taskId = useVModel(props, 'taskId', emit);
const visible = useVModel(props, 'visible', emit);

const taskOptions = ref([]);
const buttonLoading = ref(false);
const taskFormRef = ref<ElFormInstance>();

const form: any = {
  taskId: undefined,
  taskName: undefined,
  taskTypeId: undefined,
  content: undefined,
  fileName: undefined,
  expectedStartTime: undefined,
  expectedEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  // score: undefined,
  // originalScore: undefined,
  performanceId: undefined,
  handlerUserId: undefined,
  userType: undefined,
  status: undefined,
  remark: undefined,
  collaborators: []
};

const validateEndTime = (rule, value, callback) => {
  if (form.value.expectedEndTime && form.value.expectedStartTime && form.value.expectedEndTime < form.value.expectedStartTime) {
    callback(new Error('预计结束时间不能小于预计开始时间'));
  } else {
    callback();
  }
};

const rules: any = {
  taskId: [{ required: false, message: '不能为空', trigger: 'blur' }],
  taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  taskTypeId: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
  content: [{ required: true, message: '任务内容不能为空', trigger: 'blur' }],
  actualStartTime: [{ required: true, message: '实际开始时间不能为空', trigger: 'blur' }],
  actualEndTime: [{ required: true, message: '实际结束时间不能为空', trigger: 'blur' }],
  // score: [{ required: true, message: '绩效分不能为空', trigger: 'blur' }],
  performanceId: [{ required: true, message: '业绩目标不能为空', trigger: 'blur' }],
  handlerUserId: [{ required: true, message: '处理人不能为空', trigger: 'blur' }],
  userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '任务状态不能为空', trigger: 'change' }],
  remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }],
  expectedStartTime: [{ required: true, message: '预计开始时间不能为空', trigger: 'blur' }],
  expectedEndTime: [
    { required: true, message: '预计结束时间不能为空', trigger: 'blur' },
    { validator: validateEndTime, trigger: 'blur' }
  ]
};

const xtId = computed(() => {
  return taskOptions.value.find((item) => item.name === '协调任务')?.id;
});

const getTaskInfo = async () => {
  let res = await getTask(taskId.value);
  Object.assign(form.value, res.data);
  dialog.title = '修改任务';
};

/** 提交按钮 */
const submitForm = () => {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.taskId) {
        await updateTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTask(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
    }
  });
};

const init = async () => {
  let res = await getTaskInfo();
  dialog.visible = true;
};

onMounted(async () => {});
</script>
